package com.canplay.screen.ui.view

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.canplay.screen.R
import com.canplay.screen.adapter.LoopLayoutManager
import com.canplay.screen.adapter.MyAdapter
import com.canplay.screen.adapter.setupLoopingLayoutManager
import com.canplay.screen.base.BaseActivity
import com.canplay.screen.common.ConstClass
import com.canplay.screen.common.ConstClass.Companion.IS_QUERY
import com.canplay.screen.common.ConstClass.Companion.LOG_TAG
import com.canplay.screen.common.ConstClass.Companion.SP_VERSION
import com.canplay.screen.db.DataItem
import com.canplay.screen.db.DataLocateDataSource
import com.canplay.screen.event.MessageEvent
import com.canplay.screen.init.appContext
import com.canplay.screen.network.ApiService
import com.canplay.screen.repository.MyRepository
import com.canplay.screen.response.RequestCallback
import com.canplay.screen.service.CheckTimeService
import com.canplay.screen.utils.DataHelper
import com.canplay.screen.utils.NetworkUtils
import com.canplay.screen.utils.ScreenUtils
import com.canplay.screen.utils.ThreadUtils
import com.canplay.screen.utils.TimeUtils
import com.canplay.screen.utils.ToastUtils
import com.wang.avi.AVLoadingIndicatorView
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone

class MainActivity : BaseActivity() {

    private lateinit var loading: AVLoadingIndicatorView;
    private lateinit var recyclerView: RecyclerView;
    private lateinit var txVersion: TextView;
    private lateinit var txTotal: TextView;
    private lateinit var txTitle: TextView;
    private lateinit var image: ImageView;

    private lateinit var myRepository: MyRepository;

    private lateinit var dataLocateDataSource: DataLocateDataSource

    private var showData = ArrayList<DataItem>()

    private lateinit var adapter: MyAdapter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main_layout);

        loading = findViewById(R.id.avi);
        recyclerView = findViewById(R.id.recyclerView)
        txVersion = findViewById(R.id.tx_version)
        txTotal = findViewById(R.id.tx_total)
        txTitle = findViewById(R.id.tx_title)
        image = findViewById(R.id.image)
        dataLocateDataSource = DataLocateDataSource()

        myRepository = MyRepository(ApiService.create(), dataLocateDataSource);

        initSize()

        initRecycleVie()
        queryVersion()
    }


    override fun onResume() {
        super.onResume()
        hideSystemUI()
    }

    private fun initSize() {
        txTitle.setTextSize(
            TypedValue.COMPLEX_UNIT_DIP, ScreenUtils.getResultDP(appContext.resources, 20)
        )
        txVersion.setTextSize(
            TypedValue.COMPLEX_UNIT_DIP, ScreenUtils.getResultDP(appContext.resources, 15)
        )
        txTotal.setTextSize(
            TypedValue.COMPLEX_UNIT_DIP, ScreenUtils.getResultDP(appContext.resources, 15)
        )

        image.postDelayed({
            val layoutParams = image.layoutParams
            layoutParams.height = ScreenUtils.dp2Px(
                appContext.resources, ScreenUtils.getResultDP(appContext.resources, 25).toInt()
            )
            layoutParams.width = (1970 * layoutParams.height / 1114).toInt() // 设置宽度
            image.layoutParams = layoutParams
        }, 0)
    }


    private fun initRecycleVie() {

        adapter = MyAdapter(showData)
        recyclerView.layoutManager = LoopLayoutManager(this)
        recyclerView.adapter = adapter
        //设置循环数据
        recyclerView.setupLoopingLayoutManager()
        //1秒钟 滚动 100像素
        recyclerView.autoScroll(1000L, 150)
    }

    private fun queryVersion() {

        val networkAvailable = NetworkUtils.isNetworkAvailable(appContext)

        if (networkAvailable) {
            var version = DataHelper.getStringSF(appContext, SP_VERSION) ?: ""
            kotlinx.coroutines.runBlocking {
                val versionRes = myRepository.getVersionInfo()
                val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
                format.timeZone = TimeZone.getTimeZone("UTC") // 设置时区为 UTC
                val dataTime = versionRes?.getResponseData()
                if (dataTime != null) {
                    var responseData = ""
//                      responseData = TimeUtils.dateToString(
//                            format.parse(versionRes?.getResponseData()),
//                            TimeUtils.PATTERN_YYYY_MM_DD

                    responseData = TimeUtils.longToString(
                        dataTime, TimeUtils.PATTERN_YYYY_MM_DD
                    )

                   var responseCacheData = TimeUtils.longToString(
                        dataTime, TimeUtils.PATTERN_YYYY_MM_DD_HH_MM_SS
                    )

                    Log.d(LOG_TAG, "queryVersion: $responseCacheData")

                    ThreadUtils.runOnUiThread {
                        txVersion.text = "版本号: $responseData"
                    }
                    if (version != responseCacheData) {//版本号不一致 或者 本地没有版本号
                        queryAllData(true);
                    } else { //本地有版本号 去拿缓存
                        queryAllData(false);
                    }
                    DataHelper.setStringSF(appContext, SP_VERSION, responseCacheData)
                } else {
                    try{
                        ThreadUtils.runOnUiThread {
                            txVersion.text = "版本号: ${TimeUtils.dateToString(TimeUtils.stringToDate(
                                version) , TimeUtils.PATTERN_YYYY_MM_DD
                            )}"
                        }
                    }catch (e:Exception){}
                    ToastUtils.toast("获取版本号失败")
                    loading.hide()
                    queryAllData(false)
                }
            }
        } else {
            var version = DataHelper.getStringSF(appContext, SP_VERSION) ?: ""
            if(version!=""){
                try{
                    ThreadUtils.runOnUiThread {
                        txVersion.text = "版本号: ${TimeUtils.dateToString(TimeUtils.stringToDate(
                            version) , TimeUtils.PATTERN_YYYY_MM_DD
                        )}"
                    }
                }catch (e:Exception){}
            }
            queryAllData(false)
        }
    }

    private fun queryAllData(needNet: Boolean = false) {
        kotlinx.coroutines.runBlocking {
            val allData: List<DataItem> = dataLocateDataSource.getAllDate();
            if (allData.isNotEmpty()) {
                Log.d(LOG_TAG, "所有数据缓存，共${allData.size}条:${allData.toString()}")
                showData.clear()
                ThreadUtils.runOnUiThread {
                    txTotal.text = "共:${allData.size}条"
                }
                showData.addAll(allData)
                adapter.notifyDataSetChanged()
                recyclerView.scrollToPosition(0)
                if (needNet) {//先用本地的数据，再去网络请求
                    queryByNetWork()
                } else {
                    if (!ToastUtils.isToastShowing()) {
                        ToastUtils.toast("加载数据成功,共${allData.size}条")
                    }
                    loading.hide()
                    startMyService()
                }
            } else {//缓存不存在，直接去网络请求
                queryByNetWork()
            }
        }
    }

    private fun queryByNetWork() {
        val requestCallBack = object : RequestCallback {
            override fun isSuccess(list: ArrayList<DataItem>) {
                showData.clear()
                showData.addAll(list)
                if (!ToastUtils.isToastShowing()) {
                    ToastUtils.toast("加载数据成功,共${list.size}条")
                }
                ThreadUtils.runOnUiThread {
                    txTotal.text = "共: ${list.size} 条"
                }
                adapter.notifyDataSetChanged()
                recyclerView.scrollToPosition(0)
                loading.hide()
                startMyService()
            }

            override fun isFail() {
                loading.hide()
                ToastUtils.toast("加载数据失败")
            }

        }
        myRepository.getAllDate(requestCallBack)
    }


    fun RecyclerView.autoScroll(delayMillis: Long, speed: Int) {
        val handler = Handler()
        val runnable = object : Runnable {
            override fun run() {
                val firstVisibleItem =
                    (layoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition() ?: 0
                val lastVisibleItem =
                    (layoutManager as? LinearLayoutManager)?.findLastVisibleItemPosition() ?: 0
                val itemCount = adapter?.itemCount ?: 0

                if (
//                    firstVisibleItem != lastVisibleItem
//                    &&
                    lastVisibleItem < itemCount - 1) {
                    smoothScrollBy(0, speed)
                    handler.postDelayed(this, delayMillis)
                } else {
                    scrollToPosition(0)
                    handler.postDelayed(this, delayMillis)
                }
            }
        }
        handler.postDelayed(runnable, delayMillis)
    }


    private fun hideSystemUI() {
        window.decorView.systemUiVisibility =
            (View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LOW_PROFILE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.decorView.systemUiVisibility =
                (window.decorView.systemUiVisibility or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        }
    }

    override fun onMessageEvent(event: MessageEvent) {
        super.onMessageEvent(event)
        if (event.message == ConstClass.CHECK_TIME_MESSAGE) {
            queryVersion()
        }
    }


    private fun startMyService() {
        var intent = Intent(this, CheckTimeService::class.java)
        startService(intent)
    }

    override fun onDestroy() {
        var intent = Intent(this, CheckTimeService::class.java)
        stopService(intent)
        super.onDestroy()
    }
}
